package com.yunchang.springboot.scheduled.mwsfinance;

import com.yunchang.springboot.base.BaseService;
import com.yunchang.springboot.mapper.mwsfinance.FInventoryDailyMapper;
import com.yunchang.springboot.mapper.mwsreport.MwsCustomerShipmentSalesMapper;
import com.yunchang.springboot.mapper.mwsreport.MwsDailyInventoryHistoryMapper;
import com.yunchang.springboot.models.mwsfinance.FFbaShipmentSales;
import com.yunchang.springboot.models.mwsreportbean.MwsCustomerShipmentSales;
import com.yunchang.springboot.utils.DateUtil;
import com.yunchang.springboot.utils.StringUtil;
import com.yunchang.springboot.utils.UUIDUtil;
import com.yunchang.springboot.utils.mwsutils.GetCountryByCurrency;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * 已完成订单
 */
@Component
@Configuration
@Service
@Slf4j
@EnableScheduling
public class FFbaShipmentSalesScheduled extends BaseService {

    static  Integer  LIMIT_VALUE = 10000;

    static final List<String> EU_COUNTRY_LIST = Arrays.asList("DE", "FR", "IT", "UK", "ES");

    private static List<String> EUROPE_COUNTRY_NAME = Arrays.asList("DE", "UK", "FR", "IT", "ES");

    static final String EU = "EU";

    static final String US = "US";

    static final String CA = "CA";

    static final String MX = "MX";

    static final String JP = "JP";

    static String DOCUMENTS_ID = "XSCKD";

    /**
     * 出入库明细
     */
    @Autowired
    FInventoryDetailsScheduled fInventoryDetailsScheduled;


    /**
     * 借方科目
     */
    private static final String DEBIT_SUBJECT_ID = "640107";

    /**
     * 贷方科目
     */
    private static final String CREDIT_SUBJECT_ID = "140603";

    /**
     * 已完成订单原始数据
     */
    private MwsCustomerShipmentSalesMapper mwsCustomerShipmentSalesMapper;

    @Autowired
    public void setMwsCustomerShipmentSalesMapper(MwsCustomerShipmentSalesMapper mwsCustomerShipmentSalesMapper) {
        this.mwsCustomerShipmentSalesMapper = mwsCustomerShipmentSalesMapper;
    }

    /**
     * 库存数据
     */
    private FInventoryDailyMapper fInventoryDailyMapper;

    @Autowired
    public void setFInventoryDailyMapper(FInventoryDailyMapper fInventoryDailyMapper) {
        this.fInventoryDailyMapper = fInventoryDailyMapper;
    }

    /**
     * 每日库存记录原始数据
     */
    private MwsDailyInventoryHistoryMapper mwsDailyInventoryHistoryMapper;

    @Autowired
    public void setMwsDailyInventoryHistoryMapper(MwsDailyInventoryHistoryMapper mwsDailyInventoryHistoryMapper) {
        this.mwsDailyInventoryHistoryMapper = mwsDailyInventoryHistoryMapper;
    }

    public void getFFbaShipmentSales(String date) {
        List<MwsCustomerShipmentSales> mwsCustomerShipmentSalesList = mwsCustomerShipmentSalesMapper.selectByFinanceStatus(1,null,date);
        Integer mwsCustomerShipmentSalesListSize = mwsCustomerShipmentSalesList.size();
        log.info("已完成订单,原始数据的数量为："+mwsCustomerShipmentSalesListSize);
        int forNum = 1;
        if(mwsCustomerShipmentSalesListSize>LIMIT_VALUE){
            forNum += mwsCustomerShipmentSalesListSize/LIMIT_VALUE;
            for(;forNum > 0;forNum--) {
                log.info("已完成订单生成财务数据的剩余次数："+forNum);
                mwsCustomerShipmentSalesList = mwsCustomerShipmentSalesMapper.selectByFinanceStatus(1, LIMIT_VALUE,date);
                mwsCustomerShipmentSalesDispose(mwsCustomerShipmentSalesList,date);
            }
        }else {
            mwsCustomerShipmentSalesDispose(mwsCustomerShipmentSalesList,date);
        }
    }

    public void mwsCustomerShipmentSalesDispose(List<MwsCustomerShipmentSales> mwsCustomerShipmentSalesList,String date) {
        if (null != mwsCustomerShipmentSalesList && !mwsCustomerShipmentSalesList.isEmpty()) {
            List<Object> fFbaShipmentSalesInsertList = new ArrayList<>();
            for (MwsCustomerShipmentSales mwsCustomerShipmentSales : mwsCustomerShipmentSalesList) {
                FFbaShipmentSales fFbaShipmentSales = new FFbaShipmentSales();
                fFbaShipmentSales.setIsInventoryDetails(1);
                fFbaShipmentSales.setDocumentsId(DOCUMENTS_ID + UUIDUtil.getUUID());
                String sellerId = mwsCustomerShipmentSales.getSellerId();
                fFbaShipmentSales.setSellerId(sellerId);
                String country = GetCountryByCurrency.getCountryByCurrency(mwsCustomerShipmentSales.getCurrency());
                if (EU_COUNTRY_LIST.contains(country)) {
                    country = "EU";
                }
                fFbaShipmentSales.setCountry(country);
                String shipmentDate = mwsCustomerShipmentSales.getShipmentDate();
                fFbaShipmentSales.setDate(shipmentDate);
                String fulfillmentCenterId = mwsCustomerShipmentSales.getFulfillmentCenterId();
                String area = mwsCustomerShipmentSales.getArea();
                String countryShip = getCountryShip(fulfillmentCenterId,area);
                if(StringUtil.isBlank(countryShip)){
                    log.info("已完成订单。获取countryShip为空，fulfillmentCenterId: "+fulfillmentCenterId+" area: "+area);
                }
                fFbaShipmentSales.setCountryShip(countryShip);
                fFbaShipmentSales.setAmazonOrderId(mwsCustomerShipmentSales.getAmazonOrderId());
                String sku = mwsCustomerShipmentSales.getSku();
                fFbaShipmentSales.setSku(sku);
                String fnSku = mwsCustomerShipmentSales.getFnsku();
                fFbaShipmentSales.setFnsku(fnSku);
                fFbaShipmentSales.setAsin(mwsCustomerShipmentSales.getAsin());
                Integer quantity = mwsCustomerShipmentSales.getQuantity();
                fFbaShipmentSales.setQuantity(quantity);
                Double costUnit = 0.0;
                Map<String,Double> costUnitMap = getCostUnit(sellerId,countryShip,sku,fnSku,CREDIT_SUBJECT_ID,date);
                if(null != costUnitMap && !costUnitMap.isEmpty()){
                    if(costUnitMap.containsKey("costUnit1")) {
                        fFbaShipmentSales.setStatus(1);
                        costUnit = costUnitMap.get("costUnit1");
                    }
                    if(costUnitMap.containsKey("costUnit2")){
                        fFbaShipmentSales.setStatus(2);
                        costUnit = costUnitMap.get("costUnit2");
                    }
                    if(costUnitMap.containsKey("costUnit3")){
                        fFbaShipmentSales.setStatus(3);
                        costUnit = costUnitMap.get("costUnit3");
                    }
                    if(costUnitMap.containsKey("costUnit4")){
                        fFbaShipmentSales.setStatus(4);
                        costUnit = costUnitMap.get("costUnit4");
                    }
                    fFbaShipmentSales.setCostUnit(costUnit);
                    fFbaShipmentSales.setAmount(new BigDecimal(quantity*costUnit).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                fFbaShipmentSales.setCurrency("RMB");
                fFbaShipmentSales.setDebitSubjectId(DEBIT_SUBJECT_ID);
                fFbaShipmentSales.setCreditSubjectId(CREDIT_SUBJECT_ID);
                fFbaShipmentSales.setCreateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
                fFbaShipmentSales.setUpdateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
                fFbaShipmentSalesInsertList.add(fFbaShipmentSales);
                mwsCustomerShipmentSales.setFinanceStatus(2);
            }
            try {
                baseInsertList(fFbaShipmentSalesInsertList);
                mwsCustomerShipmentSalesMapper.updateFinanceStatusByMwsCustomerShipmentSalesList(mwsCustomerShipmentSalesList);
                log.info("已完成订单财务数据已生成");
            } catch (Exception e) {
                log.error("插入数据时出现错误，已完成订单" + e);
                throw new RuntimeException("插入数据时出现错误，已完成订单");
            }
        } else {
            log.info("未查询到对应的已完成订单数据列表，时间为" + DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
        }
    }


    /**
     * 获取costUnit 两种方案
     * @param sellerId
     * @param country
     * @param sku
     * @return 第一种方案的key值为costUnit1 第二种方案的key值为 costUnit2
     */
    public Map<String,Double> getCostUnit(String sellerId,String country,String sku,String fnSku,String creditSubjectId,String date){
        if(!StringUtils.isEmpty(sellerId) && !StringUtils.isEmpty(country) && !StringUtils.isEmpty(sku) && !StringUtils.isEmpty(date)){
           Double amount = fInventoryDailyMapper.selectSumAmountBySellerIdAndCountryAndSkuAndCreditSubjectIdAndDate(sellerId,country,sku,"140603",date);
           Integer quantity = fInventoryDailyMapper.selectSumQuantityBySellerIdAndCountryAndSkuAndCreditSubjectIdAndDate(sellerId,country,sku,"140603",date);
            if(null != amount && null != quantity && amount != 0 && quantity != 0){
                return new HashMap<String,Double>(1){{
                   put("costUnit1",new BigDecimal(amount/quantity).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue());
                }};
            }
            Map<String,Object> amountAndQuantityMapByFnSku = fInventoryDailyMapper.selectSumAmountAndSumQuantityBySellerIdAndCountryAndFnSkuAndWarehouseAndDate(sellerId,country,fnSku,creditSubjectId,date);
            if(null != amountAndQuantityMapByFnSku && !amountAndQuantityMapByFnSku.isEmpty()){
                if(null != amountAndQuantityMapByFnSku.get("amount") && null != amountAndQuantityMapByFnSku.get("quantity")){
                    Double amount2 = new Double(amountAndQuantityMapByFnSku.get("amount").toString());
                    Integer quantity2 = new Integer(amountAndQuantityMapByFnSku.get("quantity").toString());
                    if (null != amount2 && null != quantity2 && amount2 != 0 && quantity2 != 0) {
                        return new HashMap<String, Double>(1) {{
                            put("costUnit2", new BigDecimal(amount2 / quantity2).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                        }};
                    }
                }
            }
            Map<String,Object> amountAndQuantityMap = fInventoryDailyMapper.selectSumAmountAndSumQuantityBySellerIdAndCountryAndSkuAndWarehouse(sellerId,country,sku,"140603");
            if(null != amountAndQuantityMap && !amountAndQuantityMap.isEmpty()){
                if(null != amountAndQuantityMap.get("amount") && null != amountAndQuantityMap.get("quantity")){
                    Double amount2 = new Double(amountAndQuantityMap.get("amount").toString());
                    Integer quantity2 = new Integer(amountAndQuantityMap.get("quantity").toString());
                    if (null != amount2 && null != quantity2 && amount2 != 0 && quantity2 != 0) {
                        return new HashMap<String, Double>(1) {{
                            put("costUnit3", new BigDecimal(amount2 / quantity2).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                        }};
                    }
                }
            }
        }
        log.info("获取costUnit使用默认值，已完成订单,sellerId: "+ sellerId + " country: " +country + " sku: "+sku + " date: "+date);
        return new HashMap<String, Double>(1) {{
            put("costUnit3", new BigDecimal(60).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
        }};
    }

    /**
     * 获取countryShip
     * @param fulfillmentCenterId
     * @param area
     * @return
     */
    public String getCountryShip(String fulfillmentCenterId,String area){
        String country = null;
        if (area.equals(JP)) {
            return JP;
        }
        if (EUROPE_COUNTRY_NAME.contains(area)) {
            return EU;
        }
        if (!StringUtils.isEmpty(fulfillmentCenterId)) {
            country = mwsDailyInventoryHistoryMapper.getCountryByFulfillmentCenterId(fulfillmentCenterId);
        }
        return country;
    }

}
